package com.lmind.core.gps.terminal.protocol;

import java.nio.ByteBuffer;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class MinaProtocolDecoder extends CumulativeProtocolDecoder {

	private JsonMessageCodec objectCodec = new JsonMessageCodec();
	
	private PacketCodec packetCodec = new PacketCodec();

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {

		try {
			
			if (in.remaining() < PacketConstants.HEADER_SIZE) {
				return false;
			}

			ByteBuffer buf = packetCodec.decode(in.buf());
			if (buf == null) {
				return false;
			}
			
			out.write(decodeData(buf));
			return true;

		} catch (Exception e) {
			session.close(true);
			throw e;
		}
	}

	private Object decodeData(ByteBuffer buf) throws Exception {
		return objectCodec.decode(buf);
	}

}
